/*
 * Copyright 2013-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.springframework.cloud.gateway.discovery;

import static org.springframework.cloud.gateway.filter.factory.RewritePathGatewayFilterFactory.REGEXP_KEY;
import static org.springframework.cloud.gateway.filter.factory.RewritePathGatewayFilterFactory.REPLACEMENT_KEY;
import static org.springframework.cloud.gateway.handler.predicate.RoutePredicateFactory.PATTERN_KEY;
import static org.springframework.cloud.gateway.support.NameUtils.normalizeFilterName;
import static org.springframework.cloud.gateway.support.NameUtils.normalizePredicateName;

import java.net.URI;

import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.filter.factory.RewritePathGatewayFilterFactory;
import org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;

import reactor.core.publisher.Flux;

/**
 * TODO: developer configuration, in zuul, this was opt out, should be opt in
 * TODO: change to RouteLocator? use java dsl
 * @author Spencer Gibb
 */
public class DiscoveryClientRouteDefinitionLocator implements RouteDefinitionLocator {

	private final DiscoveryClient discoveryClient;
	private final String routeIdPrefix;

	/**
	 * @param discoveryClient 注册发现客户端，用于向注册中心发起请求
	 */
	public DiscoveryClientRouteDefinitionLocator(DiscoveryClient discoveryClient) {
		this.discoveryClient = discoveryClient;
		// 路由配置编号前缀，以DiscoveryClient类名 + _
		this.routeIdPrefix = this.discoveryClient.getClass().getSimpleName() + "_";
	}

	@Override
	public Flux<RouteDefinition> getRouteDefinitions() {
		// getServices(): 调用discoveryClient获取注册在注册中心的服务列表
		return Flux.fromIterable(discoveryClient.getServices())
				// 遍历服务列表，生成对应的RouteDefinition数组
				.map(serviceId -> {
					RouteDefinition routeDefinition = new RouteDefinition();
					// 设置RouteDefinition.id
					routeDefinition.setId(this.routeIdPrefix + serviceId);
					// 设置RouteDefinition.uri，格式为lb://${serviceId}。在LoadBalancerClientFilter会根据lb://前缀过滤处理，负载均衡，选择最终调用的服务地址，在《4过滤器》-《4LoadBalancerClientFilter负载均衡》解析
					routeDefinition.setUri(URI.create("lb://" + serviceId));

					// add a predicate that matches the url at /serviceId
					/*PredicateDefinition barePredicate = new PredicateDefinition();
					barePredicate.setName(normalizePredicateName(PathRoutePredicateFactory.class));
					barePredicate.addArg(PATTERN_KEY, "/" + serviceId);
					routeDefinition.getPredicates().add(barePredicate);*/

					// 使用PathRoutePredicateFactory创建Path匹配断言。例如服务的serviceId=spring.application.name=juejin-sample，通过网关http://${gateway}/${serviceId}/some_api访问服务http://some_api，
					// PathRoutePredicateFactory在《3处理器》-《1RoutePredicateFactory路由谓语工厂》-10、PathRoutePredicateFactory有解析
					// add a predicate that matches the url at /serviceId/**
					PredicateDefinition subPredicate = new PredicateDefinition();
					subPredicate.setName(normalizePredicateName(PathRoutePredicateFactory.class));
					subPredicate.addArg(PATTERN_KEY, "/" + serviceId + "/**");
					routeDefinition.getPredicates().add(subPredicate);

					//TODO: support for other default predicates

                    // 使用RewritePathGatewayFilterFactory创建重写网关过滤器，用于移除请求路径里的/${serviceId}，如果不移除，最终请求不到服务。
					// RewritePathGatewayFilterFactory在《4过滤器》-《2GatewayFilterFactory过滤器工厂》-1、RewritePathGatewayFilterFactory有解析
					// add a filter that removes /serviceId by default
					FilterDefinition filter = new FilterDefinition();
					filter.setName(normalizeFilterName(RewritePathGatewayFilterFactory.class));
					String regex = "/" + serviceId + "/(?<remaining>.*)";
					String replacement = "/${remaining}";
					filter.addArg(REGEXP_KEY, regex);
					filter.addArg(REPLACEMENT_KEY, replacement);
					routeDefinition.getFilters().add(filter);

					//TODO: support for default filters

					return routeDefinition;
				});
	}
}
